package cn.elwy.rcp.ui.table.format;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.NumberFormat;
import java.text.ParseException;

public class DecimalColumnFormat extends ColumnFormat {

  private static final long serialVersionUID = 1L;

  public DecimalColumnFormat() {
  }

  public DecimalColumnFormat(String pattern) {
    super(pattern);
  }

  @Override
  public String format(Object value) {
    if (value == null) {
      return getDefaultValue();
    } else if (getPattern() == null) {
      return value.toString();
    }
    Format format = getFormat();
    return format.format(value);
  }

  @Override
  @SuppressWarnings("unchecked")
  public <T> T parse(String value, Class<T> clazz) throws ParseException {
    NumberFormat format = (NumberFormat) getFormat();
    return (T) format.parse(value);
  }

  @Override
  public Format getFormat() {
    Format format = super.getFormat();
    if (format == null) {
      NumberFormat numberFormat = null;
      if (getPattern() == null) {
        numberFormat = DecimalFormat.getPercentInstance();
      } else {
        numberFormat = new DecimalFormat(getPattern());
      }
      numberFormat.setRoundingMode(RoundingMode.HALF_UP);
      setFormat(numberFormat);
      format = numberFormat;
    }
    return format;
  }

}